const db = require("../../db/index");
const jwt = require('jsonwebtoken');
const config = require('../../config');
const test_handler = async ctx => {
    ctx.status = 200;
    ctx.body = { msg: "test ok!" };
}

const register_handler = async ctx => {
    // 校验规则！！！
    const { username } = ctx.request.body;
    console.log('username: ', username);
    const query_sql = "select * from users where username = ?";
    let { len } = await db.query(query_sql, username).then(res => res);
    // len 
    // len 为 undefined 说明 数据库中没有对应值 可以添加
    // len 为 1 说明 数据库中有对应值，不可以添加
    if (len > 0) return ctx.send('帐号被占用了');

    // 加密密码！！！

    const insert_sql = "insert into users set ?";
    let res = await db.query(insert_sql, ctx.request.body).then(res => res)
    // 数据库设置不能重复的username ，如果重复报错
    // 数据查询出错，直接报错，而不通过错误级中间件？？？
    if (res.affectedRows !== 1) return ctx.send('数据库操作失败');
    return ctx.send('注册操作成功', 200);
}

const login_handler = async ctx => {
    const { username, password } = ctx.request.body;
    console.log('username: ', username);
    console.log('password: ', password);

    const query_sql = 'select username,password from users where username = ?'
    let res = await db.query(query_sql, username).then(res => res);
    console.log('res: ', res);
    if (res.length == 1) {
        let result = res[0];
        if (username == result.username && password == result.password) {
            const tokenStr = jwt.sign(username, config.jwtSecretKey)
            // const tokenStr = jwt.sign(username, config.jwtSecretKey, { expiresIn: config.expiresIn })
            res.status = 200;
            res.body = {
                message: '登录成功！',
                token: 'Bearer ' + tokenStr,
            }
            return
            // ctx.response.body = {
            //     status: 200,
            //     message: '登录成功！',
            //     token: 'Bearer ' + tokenStr
            // }
        } else {
            return ctx.send("帐号或密码不正确")
        }
    }
    ctx.send("数据库查询结果异常")
}

module.exports = {
    test_handler, register_handler, login_handler
}